package handlers

import (
	pb "discover"
	"discover/discover-service/svc"
	"os"
	"time"

	"github.com/go-kit/kit/log"
	"github.com/hashicorp/consul/api"
)

// WrapEndpoints accepts the service's entire collection of endpoints, so that a
// set of middlewares can be wrapped around every middleware (e.g., access
// logging and instrumentation), and others wrapped selectively around some
// endpoints and not others (e.g., endpoints requiring authenticated access).
// Note that the final middleware wrapped will be the outermost middleware
// (i.e. applied first)
func WrapEndpoints(in svc.Endpoints) svc.Endpoints {

	// Pass a middleware you want applied to every endpoint.
	// optionally pass in endpoints by name that you want to be excluded
	// e.g.
	// in.WrapAllExcept(authMiddleware, "Status", "Ping")

	// Pass in a svc.LabeledMiddleware you want applied to every endpoint.
	// These middlewares get passed the endpoints name as their first argument when applied.
	// This can be used to write generic metric gathering middlewares that can
	// report the endpoint name for free.
	// github.com/metaverse/truss/_example/middlewares/labeledmiddlewares.go for examples.
	// in.WrapAllLabeledExcept(errorCounter(statsdCounter), "Status", "Ping")

	// How to apply a middleware to a single endpoint.
	// in.ExampleEndpoint = authMiddleware(in.ExampleEndpoint)

	return in
}

func WrapService(in pb.DiscoverServer) pb.DiscoverServer {
	//创建日志组件
	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stderr)
		logger = log.With(logger, "ts", log.TimestampFormat(time.Now, time.StampMilli))
		logger = log.With(logger, "caller", log.DefaultCaller)
	}

	//创建consul客户端对象
	// var client consul.Client
	{
		consulConfig := api.DefaultConfig()

		consulConfig.Address = "http://localhost:8500"
		consulClient, err := api.NewClient(consulConfig)

		if err != nil {
			logger.Log("err", err)
			os.Exit(1)
		}
		service, _, err := consulClient.Agent().Service("test4calc_1", nil)
		if err != nil {
			logger.Log("err", err)
			os.Exit(1)
		}
		logger.Log("service calc_1 ip", service.Address, "port", service.Port)

		serviceEntry, _, err := consulClient.Health().Service("test4", "", true, nil)
		if err != nil {
			logger.Log("err", err)
			os.Exit(1)
		}
		for _, v_ := range serviceEntry {
			s_ := v_.Service
			logger.Log("service ip", s_.Address, "port", s_.Port)
		}

		result, _, err := consulClient.Catalog().Service("test4", "", nil)
		if err != nil {
			logger.Log("err", err)
			os.Exit(1)
		}
		for _, v_ := range result {
			logger.Log("service2 ip", v_.ServiceAddress, "port2", v_.ServicePort)
		}

		// client = consul.NewClient(consulClient)
	}
	// serviceName := "test4"
	// tags := []string{"test4", "jack"}
	// passingOnly := true
	// // duration := 500 * time.Millisecond
	// //基于consul客户端、服务名称、服务标签等信息，
	// // 创建consul的连接实例，
	// // 可实时查询服务实例的状态信息
	// instancer := consul.NewInstancer(client, logger, serviceName, tags, passingOnly)
	// ch := make(chan sd.Event)
	// logger.Log("service", "111")
	// instancer.Register(ch)
	// logger.Log("service", "222")
	// for event := range ch {
	// 	logger.Log("instance", event.Instances, "Err", event.Err)
	// 	// de.cache.Update(event)
	// }

	// logger.Log("service", "333")
	return in
}
